﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace ScoreMS.Views
{
    /// <summary>
    /// Examination_paperEdit.xaml 的交互逻辑
    /// 
    /// 可接受页面传入参数 ex_id 试卷ID，若不传入，则跳转到 Examination_paperView.xaml
    /// </summary>
    public partial class Examination_paperEdit : Page, INotifyPropertyChanged
    {
        public Examination_paperEdit()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Examination_paperEdit_Loaded);
        }

        private int ex_id;
        private int problemCount;
        private int problemCur;

        public int ProblemCur
        {
            get { return problemCur; }
            set
            {
                if (problemCur != value)
                {
                    problemCur = value;
                    NotifyPropertyChanged("ProblemCur");
                }
            }
        }

        /// <summary>
        /// 题目
        /// </summary>
        private List<KeyValuePair<Model.Problem, List<int>>> problems;

        /// <summary>
        /// 初始化
        /// </summary>
        private void init()
        {
            this.cbxproblem_difficulty.ItemsSource = new List<string>()
            {
                "难","较难","适中","易"
            };
            this.cbxproblem_type.ItemsSource = new List<string>()
            {
                "基本知识题", "综合性题", "提高性题"
            };
        }

        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Examination_paperEdit_Loaded(object sender, RoutedEventArgs e)
        {
            var param = App.Current.Properties["frame"];    //接受页面传入的参数 ex_id
            if (param != null)
            {
                this.DataContext = this;
                this.NumBig.ValueChangedEvent += new ScoreMS.Controls.NumericUpDown.ValueChangedEventHandler(NumBig_ValueChangedEvent);
                init();

                ex_id = int.Parse(param.ToString());
                string course_id = BLL.Examination_paparBS.GetCourseID(ex_id);
                lblCourse.Text = course_id;
                lblEx_id.Text = ex_id.ToString();
                problemCount = BLL.Examination_paparBS.GetProblemCount(ex_id);
                ProblemCur = 1;
                lblProblemCount.Text = "/" + problemCount.ToString();

                var model = BLL.Examination_paparBS.GetExamination_papar(ex_id);
                NumBig.MaxValue = model.bigquestion_count;
                NumSmall.MaxValue = model.smallquestion_count;  //只是一个最值，每大题的小题数是用户确定的。

                //对已录入题目的试卷进行检查
                int preparedProblemCount = BLL.Examination_paparBS.GetPreparedProblemCount(ex_id);
                if (preparedProblemCount != 0 && MessageBox.Show("此试卷已成功录入" + (preparedProblemCount == BLL.Examination_paparBS.GetProblemCount(ex_id) ? ("所有题目") : ("过" + preparedProblemCount.ToString() + "道题目")) + "。是否重新录入？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.No)
                {
                    NavigationService.Navigate(new Uri("Views/Examination_paperView.xaml", UriKind.Relative));
                }
                else if (preparedProblemCount != 0)
                {
                    //ToDo: 删除此试卷的相关题目
                }

                this.lstSyllabus.ItemsSource = BLL.CourseBS.GetCourse_syllabusList(course_id);
                problems = new List<KeyValuePair<Model.Problem, List<int>>>(); //题目Buffer
            }
            else
            {
                MessageBox.Show("请选择一份试卷！", "提示");
                NavigationService.Navigate(new Uri("Views/Examination_paperView.xaml", UriKind.Relative));
            }
        }

        /// <summary>
        /// 添加当前题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, RoutedEventArgs e)    //ToDo：大小题号，暂时需要人为控制
        {
            if (txtproblem_points.Text.Trim() == ""
                || cbxproblem_difficulty.SelectedIndex == -1
                || cbxproblem_type.SelectedIndex == -1)
            {
                MessageBox.Show("请填写完整！", "提示");
                return;
            }
            int problem_points;
            if (!int.TryParse(txtproblem_points.Text.Trim(), out problem_points))
            {
                MessageBox.Show("注意“题分”应为阿拉伯数字，如4", "警告");
                return;
            }
            if (lstSyllabus.SelectedItems.Count == 0)
            {
                if (MessageBox.Show("不为该题添加所涉及的知识点？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.No)
                {
                    return;
                }
            }

            var syllabuses = new List<int>();
            foreach (var item in lstSyllabus.SelectedItems)
            {
                syllabuses.Add((item as Model.Course_syllabus).syllabus_index);
            }
            problems.Add(new KeyValuePair<Model.Problem, List<int>>(new Model.Problem()
            {
                ex_id = ex_id,
                problem_id = ProblemCur,
                bigquestion_id = NumBig.Value,
                smallquestion_id = NumSmall.Value,
                problem_points = problem_points,
                problem_difficulty = cbxproblem_difficulty.SelectedValue.ToString(),
                problem_type = cbxproblem_type.SelectedValue.ToString()
            },
            syllabuses));

            if (ProblemCur < problemCount)
            {
                ProblemCur++;
                txtproblem_points.Clear();
                NumSmall.Value++;
                lstSyllabus.SelectedItems.Clear();      //ok?
            }
            else    //写入数据库
            {
                //foreach (var problem in problems)
                for(int index=0; index<problems.Count; index++)
                {
                    var problem = problems[index];
                    if (!BLL.ProblemBS.AddProblem(problem.Key, problem.Value))  //ToDo：写成数据库事务啊 = =！
                    {
                        MessageBox.Show("第" + (index + 1).ToString() + "题：添加失败！请确保输入数据正确！", "警告");
                        return;
                    }
                }
                MessageBox.Show("恭喜！添加成功！", "提示");
                NavigationService.Navigate(new Uri("Views/Examination_paperView.xaml", UriKind.Relative));
            }
        }

        /// <summary>
        /// 回到上一题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLastProblem_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("回到上一题会清空在他之后录入的题。是否继续？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.No)
            {
                return;
            }
            if (problems.Count == ProblemCur)
            {
                problems.RemoveAt(problems.Count - 1);  //把最后一个删掉
            }
            ProblemCur--;
            var problem = problems[ProblemCur-1];
            NumBig.Value = problem.Key.bigquestion_id;
            NumSmall.Value = problem.Key.smallquestion_id;
            txtproblem_points.Text = problem.Key.problem_points.ToString();
            cbxproblem_difficulty.SelectedValue = problem.Key.problem_difficulty;
            cbxproblem_type.SelectedValue = problem.Key.problem_type;
            lstSyllabus.SelectedItems.Clear();
            foreach (var syllabus_index in problem.Value)
            {
                foreach (var item in lstSyllabus.Items)
                {
                    if ((item as Model.Course_syllabus).syllabus_index == syllabus_index)
                    {
                        lstSyllabus.SelectedItems.Add(item);    //ok?
                    }
                }
            }
        }

        /// <summary>
        /// 当大题号改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void NumBig_ValueChangedEvent(object sender, EventArgs e)
        {
            NumSmall.Value = 1; //小题号归1
        }

        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
}
